import MySQLdb
import sys
import time

# usage example: $python importer/firewall.py pwd sample_ori_firewall sample/Firewall_Log.txt

DEBUG = 2

DIRDICT = {'inbound': 1, 'outbound': -1, '(empty)':0}

if __name__ == '__main__':
    db = MySQLdb.connect(host="rome.cs.vt.edu", port=5801, user="fusetester", passwd=sys.argv[1], db="fusebox")

    tablename = sys.argv[2]
    filename = sys.argv[3]
    hfile = open(filename)

    if DEBUG >= 2:
        print '#### start ####'

    hfile.readline() # skip the table header

    counter = 1
    for line in hfile.readlines():
        items = line.split(',')

        if DEBUG >= 3:
            print '#### ITEM ####'
            print items

        unixdate = int(time.mktime(time.strptime(items[0], "%d/%b/%Y %H:%M:%S")))
        priority, operation, message, protocol, sip, dip = items[1:7]
        sport, dport, dservice, directionstr, flagconnst, flagconned = items[9:]
        direction = DIRDICT[directionstr]
        if sport == '(empty)':
            sport = 0
        if dport == '(empty)':
            dport = 0
        if len(priority) > 16 or len(protocol) > 16:
            print 'Warning: priority or protocol field is out of space!'
        if len(message) > 1024:
            print 'Warning: message field is out of space!'
        if len(dservice) > 16:
            print 'Warning: dest service field is out of space!'

        db.query('INSERT INTO %s (date, priority, operation, message, protocol, sip, dip, sport, dport, dservice, direction, connb, connd) VALUES (%d, "%s", "%s", "%s", "%s", "%s", "%s", %s, %s, "%s", %d, %s, %s)' % (tablename, unixdate, priority, operation, message, protocol, sip, dip, sport, dport, dservice, direction, flagconnst, flagconned))

        if DEBUG >= 3:
            print '#### END %d ####' % (counter)
        if DEBUG >= 2 and counter % 1000 == 0:
            print '#### END %d ####' % (counter)
        counter += 1

    db.close()

